<?php

namespace App\GraphQL\Mutations\User;

use GraphQL\Type\Definition\ResolveInfo;
use Nuwave\Lighthouse\Support\Contracts\GraphQLContext;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;
use App\Models\User;
class UpdateCreateGroupStatus
{
    /**
     * Return a value for the field.
     *
     * @param  null  $rootValue Usually contains the result returned from the parent field. In this case, it is always `null`.
     * @param  mixed[]  $args The arguments that were passed into the field.
     * @param  \Nuwave\Lighthouse\Support\Contracts\GraphQLContext  $context Arbitrary data that is shared between all fields of a single query.
     * @param  \GraphQL\Type\Definition\ResolveInfo  $resolveInfo Information about the query itself, such as the execution state, the field name, path to the field from the root, and more.
     * @return mixed
     */
    public function __invoke($rootValue, array $args, GraphQLContext $context, ResolveInfo $resolveInfo)
    {
        $user = $this->validate($args);
        $user->create_group = $args['status'];
        $user->save();
        return [
            'status'=> '200',
            'message'=>'更新成功'
        ];
    }
    public function validate($data){
        $authUser = auth()->user();
        if ($authUser->role_code !== 'ADMIN') {
            throw new \Exception('没有权限');
        }
        $rules = [
            'id'=>['required'],
            'status'=>['required',Rule::in(['Y','N'])]
        ];
        $messages = [
            'id.required'=>'id不能为空',
            'status.required'=>'状态不能为空',
            'status.in'=>'状态不能超出限制'
        ];
        $validate = Validator::make($data,$rules,$messages);
        if ($validate->fails()) {
            throw new \InvalidArgumentException($validate->messages()->first());
        }
        // 验证用户是否存在
        $old = User::find($data['id']);
        if(!$old){
            throw new \Exception('用户不存在!');
        }
        return $old;
    }
}
